package hash;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 和为 k 的子数组
 *
 * 连续子数组的和为0，求有多少个这样的子数组
 *
 * https://leetcode-cn.com/problems/subarray-sum-equals-k/
 */
@Slf4j
public class SubarraySum {

    public static void main(String[] args) {
//        int[] nums = {1,1,1};
//        int k = 2;
        int[] nums = {3, 4, 7, 2, -3, 1, 4, 2};
        int k = 7;
        int res = new SubarraySum().subarraySum0(nums, k);
        System.out.println(res);
    }

    public int subarraySum0(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int count = 0;
        for (int start = 0; start < nums.length; start++) {
            int sum = 0;
            for (int end = start; end >= 0; end--) {
                sum += nums[end];
                if (sum == k) {
                    count++;
                }
            }
        }
        return count;
    }

    public int subarraySum1(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int count = 0;
        for (int start = 0; start < nums.length; ++start) {
            int sum = 0;
            for (int end = start; end >= 0; --end) {
                sum += nums[end];
                if (sum == k) {
                    count++;
                    log.info("start: {}, end: {}", start, end);
                }
            }
        }
        return count;
    }

    public int subarraySum2(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        // 转成数组和
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 1; i < nums.length; i++) {
            nums[i] += nums[i - 1];
        }

        int count = 0;
        int pre;
        map.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i] - k)) {
                count += map.get(nums[i] - k);
            }
            pre = map.containsKey(nums[i]) ? map.get(nums[i]) + 1 : 1;
            map.put(nums[i], pre);
        }
        return count;
    }

}
